<template>
  <el-container class="list">
    <el-aside width="180px">
      <template v-if="isAdmin">
        <el-input placeholder="请输入分类名称/用户名" v-model="categoryFilterText"></el-input>
        <el-tree
            ref="adminCategoryTree"
            :default-expand-all="true"
            :data="adminCategoryList"
            :props="personOption"
            :check-on-click-node="true"
            :current-node-key.sync="activeName"
            :filter-node-method="filterCategory"
            @node-click="nodeClick"
            class="custom-tree">
        </el-tree>
      </template>
      <template v-else>
        <ul class="menu">
          <li :index="item.categoryValue"
              :key="item.categoryValue"
              v-for="item in typeList"
              :class="{'is-active':item.categoryValue===activeName}"
              @click="handleSelect(item.categoryValue)">
            <i class="el-icon-s-order"></i>
            {{item.categoryKey}}
          </li>
        </ul>
        <el-divider></el-divider>
        <el-button type="primary" :disabled="shareType===0" @click="hasShare(0)">已分享</el-button>
        <el-button type="success" :disabled="shareType===1" @click="hasShare(1)">被分享</el-button>

      </template>
    </el-aside>
    <el-container v-if="activeName" class="is-vertical">
      <el-header class="content__header">
        <p class="avue-tip-title">选择下面的方式进行创建</p>
        <div class="content__box content__nav">
          <div class="content__add"
               @click="handleAdd">
            <img src="`${$router.options.base}img/new-project.png`"
                 height="40px"
                 alt="">
            <p>新建大屏</p>
          </div>
          <div class="content__page">
            <el-pagination v-if="page.total>0"
                           layout="total, sizes, prev, pager, next, jumper"
                           background
                           size="mini"
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :page-size="page.size"
                           :current-page="page.page"
                           :total="page.total">
            </el-pagination>
          </div>
        </div>
      </el-header>
      <el-main class="content">
        <div class="content__box">
          <div class="content__item"
               v-for="(item,index) in visualList"
               :key="index"
               @mouseover="item._menu=true"
               @mouseout="item._menu=false">
            <div class="content__info">
              <img v-if="item.backgroundUrl"
                   :src="item.backgroundUrl"
                   alt="" />
              <div class="content__menu"
                   v-show="item._menu">
                <div class="content__btn"
                     @click="handleViews(item)">
                  预览<i class="el-icon-view"></i>
                </div>
                <div class="content__btn"
                     @click="handleEdit(item)">
                  开发<i class="el-icon-setting"></i>
                </div>
                <div class="content__btn"
                     @click="handleExport(item)">
                  导出
                </div>
              </div>
            </div>
            <div class="content__main">
              <span class="content__name">{{item.title}}</span>
              <div class="content__menulist">
                <div class="content__view">
                  <el-tooltip content="删除">
                    <i class="el-icon-delete"
                       @click="handleDel(item,index)"></i>
                  </el-tooltip>
                  <el-tooltip content="编辑">
                    <i class="el-icon-edit"
                       @click="handleUpdate(item,index)"></i>
                  </el-tooltip>
                  <el-tooltip content="复制">
                    <i class="el-icon-copy-document"
                       @click="handleCopy(item,index)"></i>
                  </el-tooltip>
                  <el-tooltip content="分享">
                    <i class="el-icon-share"
                       @click="handleShare(item,index)"></i>
                  </el-tooltip>
                </div>
                <span class="content__status"
                      :class="{'content__status--active':item.status}">
                  {{item.status?'已发布':'未发布'}}
                </span>
              </div>

            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <el-container v-else>
      <!-- 调用接口来渲染分享给不同的人的情况 -->
      <el-main class="content">
        <el-collapse v-model="sharedNames" >
          <el-collapse-item v-for="(list,key,index) in sharedMap" :key="index" :title="key" :name="key">
            <template slot="title">
              <span style="font-weight: bold">{{key}}</span>
            </template>
            <el-container class="is-vertical">
              <el-main class="content">
                <div class="content__box">
                  <div class="content__item"
                       v-for="(item,index) in list"
                       :key="item.shareId"
                       @mouseover="item._menu=true"
                       @mouseout="item._menu=false">
                    <div class="content__info">
                      <img v-if="item.backgroundUrl"
                           :src="item.backgroundUrl"
                           alt="" />
                      <div class="content__menu"
                           v-show="item._menu">
                        <div class="content__btn"
                             @click="handleViews(item)">
                          预览<i class="el-icon-view"></i>
                        </div>
                        <div class="content__btn" v-if="(shareType===0 ||(shareType ===1 && item.shareUserRole ===1))"
                             @click="handleEdit(item)">
                          开发<i class="el-icon-setting"></i>
                        </div>
                        <div class="content__btn"
                             @click="handleExport(item)">
                          导出
                        </div>
                      </div>
                    </div>
                    <div class="content__main">
                      <span class="content__name">{{item.title}}</span>
                      <div class="content__menulist">
                        <div class="content__view">
                          <el-tooltip content="移除分享" >
                            <i class="el-icon-remove-outline"
                               @click="handleShareRemove(item,index)"></i>
                          </el-tooltip>
                          <el-tooltip content="编辑" v-if="shareType!==1">
                            <i class="el-icon-edit"
                               @click="handleUpdate(item,index)"></i>
                          </el-tooltip>
                          <el-tooltip content="复制">
                            <i class="el-icon-copy-document"
                               @click="handleCopy(item,index)"></i>
                          </el-tooltip>
                          <el-tooltip content="分享" v-if="shareType!==1">
                            <i class="el-icon-share"
                               @click="handleShare(item,index)"></i>
                          </el-tooltip>
                        </div>
                        <span class="content__status"
                              :class="{'content__status--active':item.status}">
                  {{item.status?'已发布':'未发布'}}
                </span>
                      </div>

                    </div>
                  </div>
                </div>
              </el-main>
            </el-container>
          </el-collapse-item>
        </el-collapse>
      </el-main>
    </el-container>
    <el-dialog title="编辑大屏"
               width="50%"
               :close-on-click-modal="false"
               :visible.sync="box">
      <avue-form :option="option"
                 v-model="form"
                 @submit="handleSave"></avue-form>
    </el-dialog>

    <el-dialog title="复制大屏"
               width="50%"
               :close-on-click-modal="false"
               :visible.sync="copy">
      <avue-form :option="copyOption"
                 v-model="copyForm"
                 @submit="confirmCopy"></avue-form>
    </el-dialog>
    <el-dialog title="分享"
               width="50%"
               :close-on-click-modal="false"
               :visible.sync="userShare">
      <avue-form :option="userShareOption"
                 v-model="userShareForm"
                 @submit="confirmUserShare"></avue-form>
    </el-dialog>
  </el-container>
</template>
<script>
import {copyObj, delObj, getCategory, getList, getObj, updateObj} from '@/api/visual';
import {viewHtml} from '@/utils/html'
import {mapGetters} from "vuex";
import {getListFromUsers} from "@/api/category";
import {deepClone} from "@/echart/util";
import {removeShare, share2User, userSharedList} from "@/api/share";
import {groupBy} from "@/utils/utils";

export default {
  name: "list",
  data () {
    return {
      personList:[], // 个人的大屏设计器
      personOption:{
        label: 'categoryKey',
        value: 'categoryValue',
        children: 'children'
      },
      typeList: [],
      categoryLoading: false,
      categoryFilterText: '',
      shareType: undefined,
      box: false,
      copy: false,
      userShare: false,
      userShareForm: {},
      sharedMap: {},
      option: {
        submitText: '修改大屏',
        column: [{
          label: '分组',
          prop: 'category',
          span: 24,
          labelWidth: 100,
          type: 'select',
          dicUrl: this.$website.url + '/category/list',
          props: {
            label: 'categoryKey',
            value: 'categoryValue',
          },
          rules: [{
            required: true,
            message: "请选择分组",
            trigger: "blur"
          }]
        }, {
          label: '大屏名称',
          span: 24,
          labelWidth: 100,
          prop: 'title',
          rules: [{
            required: true,
            message: "请输入大屏名称",
            trigger: "blur"
          }]
        }, {
          label: '密码',
          span: 24,
          type: 'password',
          labelWidth: 100,
          prop: 'password',
        }, {
          label: '发布状态',
          prop: 'status',
          span: 24,
          labelWidth: 100,
          type: 'select',
          dicData: [{
            label: '未发布',
            value: 0
          }, {
            label: '已发布',
            value: 1
          }]
        }]
      },
      copyOption: {
        submitText: '确认复制',
        column: [{
          label: '分组',
          prop: 'category',
          span: 24,
          labelWidth: 100,
          type: 'select',
          dicUrl: this.$website.url + '/category/list',
          props: {
            label: 'categoryKey',
            value: 'categoryValue',
          },
          rules: [{
            required: true,
            message: "请选择分组",
            trigger: "blur"
          }]
        }, {
          label: '大屏名称',
          span: 24,
          labelWidth: 100,
          prop: 'title',
          rules: [{
            required: true,
            message: "请输入大屏名称",
            trigger: "blur"
          }]
        }, {
          label: '密码',
          span: 24,
          type: 'password',
          labelWidth: 100,
          prop: 'password',
        }, {
          label: '发布状态',
          prop: 'status',
          span: 24,
          labelWidth: 100,
          type: 'select',
          dicData: [{
            label: '未发布',
            value: 0
          }, {
            label: '已发布',
            value: 1
          }]
        }]
      },
      userShareOption: {
        submitText: '分享给个人',
        emptyBtn:false,
        column: [ {
          label: '大屏名称',
          span: 24,
          labelWidth: 100,
          prop: 'title',
          disabled: true,
          rules: [{
            required: true,
            message: "请输入大屏名称",
            trigger: "blur"
          }]
        }, {
          label: '用户',
          span: 24,
          labelWidth: 100,
          type: 'select',
          multiple: true,
          remote: true,
          prop: 'userIds',
          props: {
            label: 'name',
            value: 'id'
          },
          dicUrl: this.$website.url+`/user/list?keywords={{key}}`,
          rules:[
            {required: true,message: '请选择用户',trigger: 'blur'}
          ]
        }, {
            label: '分配角色',
            prop: 'role',
            span: 24,
            labelWidth: 100,
            type: 'select',
            dicData: [{
              label: '查看角色',
              value: 0
            }, {
              label: '管理角色',
              value: 1
            }],
          rules:[
            {required: true,message: '请选择一个角色',trigger: 'blur'}
          ]
          }]
      },
      page: {
        page: 1,
        size: 50,
        total: 0,
      },
      form: {},
      copyForm: {},
      activeName: '',
      visualList: [],
    }
  },
  created () {
  },
  mounted() {
  },
  watch: {
    categoryFilterText(val){
      this.$refs.adminCategoryTree.filter(val)
    },
    isAdmin:{
      handler(val){
        if(val){
          this.getPersonCategory()
        }else {
          this.getCategory()
        }
      },
      immediate: true
    }
  },
  computed:{
    ...mapGetters([
        "isAdmin"
    ]),
    adminCategoryList: function (){
      let result =[]
      for(const per of this.personList){
        let person={
          categoryKey: per.name,
          categoryValue: per.id,
          children: per.categoryList
        }
        result.push(person)
      }
      return result
    },
    sharedNames: {
      get: function (){
        let result =[]
        Object.keys(this.sharedMap).forEach(function (key){
          result.push(key)
        })
        return result
      },
      set: function (value){
        return value
      }
    }
  },
  methods: {
    nodeClick(data){
      console.log("点击了类目",data)
      if(!data.children){
        this.handleSelect(data.categoryValue)
      }
    },
    handleSelect (key) {
      this.activeName = key;
      this.page.page = 1;
      this.shareType = null
      this.getList();
    },
    filterCategory(value,data,node){
      console.log("data",value,data,node)
      if(!value){
        return true
      }
      return data.categoryKey.indexOf(value)!== -1
    },
    vaildData (id) {
      const list = [];
      for (var i = 0; i < 20; i++) {
        list.push(i)
      }
      return list.includes(id)
    },
    getCategory () {
      getCategory().then(res => {
        const data = res.data.data;
        this.typeList = data;
        if(!this.isAdmin&& data !==null){
          this.activeName = (this.typeList[0]||{}).categoryValue
          this.getList()
        }
      })
    },
    getPersonCategory(){
      getListFromUsers().then( res =>{
        const data = res.data.data;
        this.personList = data;
      })
    },
    // 切换分享
    hasShare(value) {
      this.shareType = value
      this.activeName = ''
      this.sharedMap={}
      this.getUserSharedList()
    },
    handleExport (item) {
      getObj(item.id).then(res => {
        const data = res.data.data;
        let mode = {
          detail: JSON.parse(data.config.detail),
          component: JSON.parse(data.config.component)
        }
        var zip = new window.JSZip();
        zip.file("view.js", `const option =${JSON.stringify(mode, null, 4)}`);
        zip.file('index.html', viewHtml);
        zip.generateAsync({ type: "base64" })
          .then(function (content) {
            location.href = "data:application/zip;base64," + content;
          });
      })
    },
    handleCopy (item) {
      if (this.$website.isDemo) {
        this.$message.error(this.$website.isDemoTip)
        return
      }
        this.copyForm = deepClone(item)
        this.copyForm.category = item.category + '';
        this.copyForm.title = 'COPY_'+ item.title;
        this.copy = true;
    },
    handleShare (item,index){
      this.userShareForm ={
        visualId: item.id,
        title: item.title,
        role: 0,
        userIds: null
      }
      this.userShare = true
    },
    confirmCopy(form, done){
      copyObj(form.id,form).then((res) => {
        this.copy = false;
        this.getList();
        this.$message.success('复制成功');
        done()
        const id = res.data.data;
        this.handleEdit({ id })
      })
    },
    confirmUserShare(form,done){
      console.log("分享form",form)
      share2User(form).then(res=>{
        if(res.data.code ===0){
          this.$message.success('分享成功');
        }else {
          this.$message.error('分享失败:'+res.data.message);
        }
        done()
        this.getUserSharedList()
        this.userShare = false
      })
    },
    handleDel (item, index) {
      this.$confirm('是否确认永久删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(item.id).then(() => {
          this.getList();
          this.$message.success('删除成功')
        })
      }).catch(() => {

      });
    },
    handleShareRemove(item, index){
      this.$confirm('是否移除分享?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeShare(item).then(() => {
          this.getUserSharedList()
          this.$message.success('移除成功')
        })
      }).catch(() => {

      });
    },
    handleAdd () {
      this.$router.push({
        path: '/create', query: {
          category: this.activeName
        }
      })
    },
    handleUpdate (item, index) {
      if (this.vaildData(Number(index)) && this.$website.isDemo) {
        this.$message.error(this.$website.isDemoTip)
        return false;
      }
      this.form = item
      this.form.category = this.form.category + '';
      this.box = true;
    },
    handleEdit (item) {
      let routeUrl = this.$router.resolve({
        path: '/build/' + item.id
      })
      window.open(routeUrl.href, '_blank');
    },
    handleViews (item) {
      let routeUrl = this.$router.resolve({
        path: '/view/' + item.id
      })
      window.open(routeUrl.href, '_blank');
    },
    handleSave (form, done) {
      updateObj({
        id: this.form.id,
        category: this.form.category,
        password: this.form.password,
        status: this.form.status,
        title: this.form.title
      }).then(() => {
        done();
        this.$message.success('修改成功');
        this.getList()
        this.box = false
      })
    },
    handleCurrentChange (val) {
      this.page.page = val;
      this.getList();
    },
    handleSizeChange (val) {
      this.page.size = val;
      this.getList();
    },
    getList (category) {
      this.visualList = []
      getList({
        category: category || this.activeName,
        current: this.page.page,
        size: this.page.size,
      }).then(res => {
        const {data: {total, records}} = res.data
        this.page.total = total;
        this.visualList = records
        this.initData();
      })
    },
    getUserSharedList(){
      userSharedList(this.shareType).then(res =>{
        const data = res.data.data
        this.sharedMap = groupBy(data, (item) =>{
          return (this.shareType === 0 ? item.shareUserName : item.sourceUserName)
         })
        this.initSharedData()
      })
    },
    initData () {
      this.visualList.forEach((ele, index) => {
        this.$set(this.visualList[index], '_menu', false)
      })
    },
    initSharedData(){
      Object.values(this.sharedMap).forEach((list)=>{
        list.forEach((ele,index) =>{
          this.$set(list[index], '_menu', false)
        })
      })
    }
  }
}
</script>
<style lang="scss">
@import "../../styles/list.scss";
.el-collapse-item__arrow {
  position: relative;
}
.el-collapse-item__wrap{
  background-color: transparent;
}
</style>
